// 折线曲线（特定）
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { PrimaryC, TableC, SecuritiesCodeC, SelectC, TreeSelectC } from '../../../comps';
import propertyTypeConfig from '../../../utils/enumeratedValues/nonstandardCurveMap';
import uuid from 'es6-uuid';
import _ from 'lodash';
import { getTreebyKey } from '../../../utils/utils';

@Form.create()
class LineCurveSpecific extends React.Component {
  state = {
    newClumns: [], // 表格行
    dataSource: [], // 表格数据
    editDataSource: {}, // 编辑前数据
    isEdit: false, // 是否处于编辑状态
    isAdd: false, // 是否处于新建
    propertyOnClick: false, // 处于编辑时证券代码回填用
    curveData: [], // 曲线下拉数据
    onPropertyType: undefined, // 当前选中资产类型
  };

  // 初始化函数
  componentDidMount() {
    this.props.dispatch({
      type: 'nonstandardCurveMapM/getCurveData',
      payload: '',
      callback: (res) => {
        if (res) {
          this.setState({
            curveData: res.data.dataSource,
          });
        } else {
          this.setState({
            curveData: [],
          });
        }
      },
    });
    this.getTableData();
  }

  // 获取表格数据
  getTableData = () => {
    this.setState(
      {
        newClumns: undefined,
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'nonstandardCurveMapM/getSpecificData',
          payload: { id: localStorage.getItem('antd-pro-userId') },
          callback: (res) => {
            if (res) {
              // const newClumns = this.clumnsChange(res.data.columns)
              res?.data?.dataSource &&
                res?.data?.dataSource.forEach((item) => {
                  const temp = propertyTypeConfig.find((i) => i.value == item.propertyType);
                  item.propertyTypeSort = temp?.title || '--';
                });
              this.clumnsChange(res?.data?.columns || []);
              this.setState({
                // newClumns: res.data.columns,
                dataSource: res?.data?.dataSource || [],
              });
            } else {
              this.setState({
                newClumns: [],
                dataSource: [],
              });
            }
          },
        });
      },
    );
  };

  // 新建点击响应
  addNew = () => {
    const newDataSource = this.state.dataSource || [];
    newDataSource.unshift({
      id: uuid(32),
    });
    this.setState(
      {
        dataSource: [...newDataSource],
        isAdd: true,
        propertyOnClick: true,
      },
      () => {
        this.forData(newDataSource[0].id, 2);
      },
    );
  };

  changeData = (treeList, arr = []) => {
    treeList.map((c) => {
      arr.push(c.value);
      if (c.children && c.children.length > 0) {
        this.changeData(c.children, arr);
      }
    });
  };

  // 默认展开所有数据
  getExpandData = () => {
    const arr = [];
    this.changeData(propertyTypeConfig, arr);
    return arr;
  };

  // 表格行优化
  clumnsChange = (columns) => {
    const { editDataSource, onPropertyType, propertyOnClick } = this.state;
    columns.map((item) => {
      if (item.key == 'propertyType') {
        (item.width = '30%'),
          (item.render = (val, record) => {
            if (record.edit) {
              return (
                <TreeSelectC
                  form={this.props.form} // form对象
                  title='' // 显示名称
                  dataIndex='propertyType' // Form识别的Item ID
                  dataSource={propertyTypeConfig}
                  initialValue={record.propertyType}
                  onChange={(e) => this.propertyTypeChange(e, record.id)}
                  treeDefaultExpandAll={true}
                  treeDefaultExpandedKeys={this.getExpandData()}
                  rules={[{ required: true, message: ' ' }]}
                  filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  positionBody={true}
                />
              );
            } else {
              if (typeof val === 'object') {
                return val;
              }
              const data = getTreebyKey(propertyTypeConfig, val);
              return data?.title || '--';
            }
          });
        if (!this.state.isAdd) {
          item.sorter = (a, b) => a.propertyTypeSort.localeCompare(b.propertyTypeSort, 'zh');
        } else {
          item.sorter = false;
        }
      }
      if (item.key == 'curve') {
        item.render = (val, record) => {
          if (record.edit) {
            return (
              <SelectC
                form={this.props.form}
                dataIndex={'curve'}
                positionBody={true}
                initialValue={typeof record.curve === 'object' ? undefined : record.curve}
                dataSource={this.state.curveData}
                filterOption={(
                  input,
                  option, // 模糊搜索value 和 title
                ) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
                rules={[{ required: true, message: ' ' }]}
              />
            );
          } else {
            const findvalue = this.state.curveData.filter((item) => {
              return item.value == val;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          }
        };
      }
      if (item.key == 'securityCode') {
        (item.width = '30%'),
          (item.render = (val, record) => {
            if (record.edit) {
              return (
                <SecuritiesCodeC
                  onChange={(e) => {
                    this.props.form.setFieldsValue({
                      securityCode: e ? e.value : e,
                    });
                  }}
                  form={this.props.form}
                  initialValue={propertyOnClick ? '' : record.exchangecode && record.securityCode ? `${record.exchangecode}-${record.securityCode}` : ''}
                  dataIndex={'securityCode'}
                  titleDisplay={false}
                  noQueryForInit={this.state.isEdit ? onPropertyType == undefined : false}
                  // 新建和资产类型点击时根据资产类型的点击加载数据，编辑时根据编辑数据的资产类型加载数据
                  codeType={onPropertyType < 11 ? 'nonstandard' : onPropertyType == 12 ? 'outsourcing' : 'zgtzptPlan'}
                  queryItems={onPropertyType == 12 ? '' : { propertyType: onPropertyType }}
                  rules={[{ required: true, message: ' ' }]}
                  disabled={this.state.isEdit ? false : onPropertyType == undefined}
                  positionBody={true}
                />
              );
            } else {
              return val;
            }
          });
      }
    });
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        type: 'operate',
        width: 120,
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.editData(record.id);
            },
            rules: {
              // 禁用逻辑：某条数据处于编辑状态
              disabled: {
                items: [{ key: 'isDisabled', value: [undefined], relation: ['!='] }],
                relation: 'or',
              },
              // 隐藏逻辑：点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['!='] }] },
            },
          },
          {
            title: '删除',
            onClick: (record, index) => {
              this.deleteData(record.id);
            },
            rules: {
              // 禁用逻辑：某条数据处于编辑状态
              disabled: {
                items: [{ key: 'isDisabled', value: [undefined], relation: ['!='] }],
                relation: 'or',
              },
              // 隐藏逻辑：点击编辑时隐藏编辑和删除按钮，展示保存和取消按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['!='] }] },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveData(record.id);
            },
            rules: {
              // 隐藏逻辑：点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.cancelData(record.id);
            },
            rules: {
              // 隐藏逻辑：点击保存或取消时隐藏保存和取消按钮，展示编辑和删除按钮
              hide: { items: [{ key: 'edit', value: [undefined], relation: ['='] }] },
            },
          },
        ],
      });
    }
    this.setState({ newClumns: columns });
  };

  // 编辑点击响应
  editData = (id) => {
    const { dataSource, editDataSource, isEdit } = this.state;
    const arr = dataSource.filter((item) => item.id == id); // 匹配数据
    const editData = arr[0];
    this.setState({
      onPropertyType: editData?.propertyType,
    });

    this.setState(
      {
        isEdit: true, // 表格处于编辑状态
      },
      () => {
        this.forData(id, 1);
        setTimeout(() => {
          this.props.form.setFieldsValue({
            securityCode: editData.exchangecode && editData.securityCode ? `${editData.exchangecode}-${editData.securityCode}` : '',
          });
        }, 500);
      },
    );
  };

  // 删除点击响应
  deleteData = (id) => {
    this.props.dispatch({
      type: 'nonstandardCurveMapM/deleteSpecificData',
      payload: { id },
      callback: (res) => {
        if (res) {
          this.getTableData();
        }
      },
    });
  };

  // 保存响应
  saveData = (id) => {
    const {
      form: { validateFields },
      dispatch,
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (!err) {
        fieldsValue.id = this.state.isAdd ? undefined : id;
        const code = fieldsValue.securityCode;
        const index = code.indexOf('-');
        fieldsValue.exchangecode = code.substr(0, index);
        fieldsValue.securityCode = code.substr(index + 1);
        dispatch({
          type: 'nonstandardCurveMapM/addData',
          payload: fieldsValue,
          callback: (res) => {
            if (res) {
              this.getTableData();
              this.setState({ isEdit: false, isAdd: false, propertyOnClick: false, onPropertyType: undefined });
            }
          },
        });
      } else {
        message.error('请填写完整信息');
      }
    });
  };

  // 取消响应
  cancelData = (id) => {
    this.setState({ isAdd: false, propertyOnClick: false, onPropertyType: undefined }, () => {
      this.forData(id, 4);
    });
  };

  // 资产类型改变响应
  propertyTypeChange = (e, id) => {
    this.setState({ onPropertyType: e, propertyOnClick: true }, () => this.forData(id, 2));
  };

  // 匹配表格数据
  forData = (id, type) => {
    const { dataSource, editDataSource, isEdit } = this.state;
    const arr = dataSource.filter((item) => item.id == id); // 匹配数据
    const index = dataSource.findIndex((item) => item.id == id); // 查找数据位置
    let newEditDataSource = {};
    if (type == 1) {
      // 编辑前保存此条数据信息，以便用户取消操作赋值
      newEditDataSource = _.cloneDeep(arr[0]);
      this.setState({
        editDataSource: newEditDataSource,
      });
    }
    if (type == 1 || type == 2) {
      arr[0].edit = true;
      dataSource.map((item) => (item.isDisabled = true)); // 当有一条数据处于编辑状态时，其他数据不可编辑
      dataSource.splice(index, 1, arr[0]);
    } else if (type == 4) {
      if (isEdit) {
        // 点编辑，然后点取消操作，将数据还原到编辑之前的
        arr[0].edit = undefined;
        arr[0].propertyType = editDataSource.propertyType;
        arr[0].securityCode = editDataSource.securityCode;
        arr[0].curve = editDataSource.curve;
        dataSource.map((item) => (item.isDisabled = undefined));
        dataSource.splice(index, 1, arr[0]);
        this.setState({
          isEdit: false,
        });
      } else {
        // 点新增，然后点取消操作，删除该条数据
        dataSource.map((item) => (item.isDisabled = undefined));
        dataSource.splice(index, 1);
      }
    }
    this.setState({ dataSource: [...dataSource] }, () => this.clumnsChange(this.state.newClumns));
  };

  render() {
    const { dataSource, newClumns, isAdd, isEdit } = this.state;
    return (
      <div>
        <div style={{ margin: '16px 0' }}>
          <PrimaryC onClick={() => this.addNew()} title={'新建'} disabled={isAdd || isEdit} />
        </div>
        <div>
          <TableC columns={newClumns} dataSource={dataSource} rowKey='id' selfScrollY={true} hidePage={true} />
        </div>
      </div>
    );
  }
}

export default connect(({ nonstandardCurveMapM }) => ({ nonstandardCurveMapM }))(LineCurveSpecific);
